<template>
  <div class="media-category">
    <div class="btn-box">
      <el-button
        type="success"
        icon="el-icon-plus"
        v-permission="['media:category:add']"
        @click="add()"
      >
        新增根分类
      </el-button>
    </div>
    <p class="tips">
      视频只能挂载在没有子分类的分类项下。若分类项下有子分类，视频必须挂载在子分类下。
    </p>
    <el-table
      tree
      lazy
      border
      style="width: 1000px"
      row-key="id"
      :data="$cateTree"
      :tree-props="{ children: 'childs', hasChildren: 'true' }"
    >
      <el-table-column label="分类名称" prop="title"></el-table-column>
      <el-table-column label="分类排序(数字越大越靠下)" prop="sortnum"></el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="scope">
          <div>
            <el-button
              type="primary"
              icon="el-icon-edit"
              v-permission="['media:category:save']"
              @click="check(scope.row)"
            >
              修改
            </el-button>
            <el-button
              type="success"
              icon="el-icon-plus"
              v-permission="['media:category:sub:save']"
              @click="add(scope.row)"
              v-if="scope.row.level < 3"
            >
              新增子类
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="del(scope.row)"
              v-permission="['media:category:del']"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      :title="categoryInfo.id ? '修改分类' : '新增分类'"
      :visible.sync="categoryDialogShow"
      width="500px"
    >
      <el-form :model="categoryInfo" ref="categoryInfoForm" @submit.native.prevent>
        <el-form-item prop="title" label="分类名称">
          <el-input v-model.trim="categoryInfo.title" @keyup.enter.native="saveCategory"></el-input>
        </el-form-item>
        <el-form-item prop="sortnum" label="分类排序(数字越大越靠下)">
          <el-input
            v-model.trim="categoryInfo.sortnum"
            @keyup.enter.native="saveCategory"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pid" label="父级分类">
          <treeselect
            v-model="categoryInfo.pid"
            :options="[{ id: 0, title: '根分类', childs: $cateTree }]"
            :normalizer="treeSelectNormalizer"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogClose">关 闭</el-button>
        <el-button
          type="success"
          v-permission="['media:category:save', 'media:category:sub:save']"
          @click="saveCategory"
          icon="el-icon-check"
          :loading="loading"
        >
          保 存
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { mapActions, mapGetters } from 'vuex';
  import Treeselect from '@riophae/vue-treeselect';
  import '@riophae/vue-treeselect/dist/vue-treeselect.css';

  export default {
    data() {
      return {
        list: [],
        selectedData: [],
        categoryInfo: {},
        categoryDialogShow: false,
        loading: false,
        searchOpt: [
          {
            type: this.SEARCH_COMP_ENUM.SEARCH_INPUT,
            name: 'title',
            label: '分类',
          },
        ],
      };
    },
    components: { Treeselect },
    mounted() {
      // this.getSortTree();
    },
    computed: {
      ...mapGetters(['$cateTree']),
    },
    methods: {
      ...mapActions(['$getCateTree']),
      /**
       * 获取分类树
       */
      getSortTree() {
        this.$service.CategoryAll().then((res) => {
          this.$getCateTree(this.coverSort(res));
        });
      },
      /**
       * TreeSelect Customize Key Names
       */
      treeSelectNormalizer(node) {
        return {
          id: node.id,
          label: node.title,
          children: node.childs,
        };
      },
      /**
       * 给数据增加好父元素的pid
       */
      coverSort(data, pid = 0, level = 0) {
        if (Array.isArray(data)) {
          return data.map((item) => {
            item.pid = pid;
            item.level = level;
            item.childs = this.coverSort(item.childs, item.id, level + 1);
            return item;
          });
        } else {
          return [];
        }
      },
      /**
       * 管理
       */
      check(row) {
        this.categoryInfo = { ...row };
        this.categoryDialogShow = true;
      },
      /**
       * 新增
       */
      add(row = {}) {
        this.categoryInfo = { pid: row.id || 0 };
        this.categoryDialogShow = true;
      },
      /**
       * 保存
       */
      saveCategory() {
        if (this.loading) return;
        this.loading = true;

        this.$service
          .CategorySave(this.categoryInfo, JSON_HEADER)
          .then((res) => {
            this.$message.success('提交成功');
            this.categoryDialogShow = false;
            this.getSortTree();
            this.dialogClose();
          })
          .finally(() => {
            this.loading = false;
          });
      },
      /**
       * 删除
       */
      del(row) {
        this.$confirm('确认要删除这个分类吗?删了就没有了', '', {
          type: 'error',
        }).then((res) => {
          this.$service
            .CategoryDelete({
              categoryId: row.id,
            })
            .then((res) => {
              this.getSortTree();
            });
        });
      },
      dialogClose() {
        this.categoryInfo = {};
        this.categoryDialogShow = false;
      },
      /**
       * 选择数据回调
       */
      selectionChange(val) {
        this.selectedData = [...val];
      },
    },
  };
</script>
